package cn.gson.crm.controller.beforesale;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.entity.Customer;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.SalesOpportunity;
import cn.gson.crm.model.mapper.OpportunityMapper;

/**
 * 机会列表 查询所有销售机会主题 根据客户id查询所有销售机会主题
 * 
 * @author PD
 *
 */
@Controller
@RequestMapping("opp")
public class OpportunityController {
	@Autowired
	OpportunityDao opdao;

	@Autowired
	CustomerDao cusdao;
	
	@Autowired
	EmployeeDao empDao;
	
	@Autowired
	OpportunityMapper oppmapper;

	@RequestMapping
	public String opp() {
		return "beforesale/opportunity";
	}

	// 加载机会列表中的表格
	@RequestMapping("oppform")
	@ResponseBody
	public Map<String, Object> form(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "2") int rows,
			HttpSession session) {
		Employee emp = (Employee) session.getAttribute("employee");
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.ASC, "id"));
		Map<String, Object> data = new HashMap<>();
		//销售主管登录，能查看到所有员工的客户的销售机会,销售员登录，只能看到自己手下的客户的销售机会
		if(emp.getRole().getRoleName().equals("销售员")){
		PageHelper.startPage(page,rows,true);
		List<SalesOpportunity> sp = oppmapper.selectOppByemp(emp.getId());
		PageInfo<SalesOpportunity> pageinfo = new PageInfo<>(sp);
			data.put("rows", pageinfo.getList());
			data.put("total", pageinfo.getTotal());
		}else{
			//查询所有
			System.out.println(emp.toString());
			Page<SalesOpportunity> sp = opdao.findAllByIsDelete(false, pr);
			data.put("rows", sp.getContent());
			data.put("total", sp.getTotalElements());
		}
		return data;
	}

	/**
	 * 加载机会列表中的新增、编辑表格
	 * 
	 * @author PD
	 * @return
	 */
	@RequestMapping({ "oppaddform/{id}", "oppaddform" })
	public String edit(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("r", opdao.findOne(id));
		}
		return "beforesale/opportunity/oppaddform";
	}

	@GetMapping("saveedit")
	@ResponseBody
	public JSONObject saveedit(@RequestParam(value="id") Long id,
			@RequestParam(value="updateTime") String updateTime,
			@RequestParam(value="expectedTime") String expectedTime,
			@RequestParam(value="topic") String topic,
			@RequestParam(value="customerid") Long customerid,
			@RequestParam(value="stage") String stage,@RequestParam(value="priority") int priority,
			@RequestParam(value="possibility") String possibility,@RequestParam(value="expectedMoney") double expectedMoney) {
			JSONObject result = new JSONObject();
			SalesOpportunity opp = opdao.findOne(id);	
			opp.setCustomer(cusdao.findOne(customerid));
			opp.setExpectedMoney(expectedMoney);
			opp.setPossibility(possibility);
			opp.setPriority(priority);
			opp.setStage(stage);
			opp.setTopic(topic);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
			//转换时间
			Date date = null;
			Date date1=null;
			try {
				date = formatter.parse(updateTime);
				date1 = formatter.parse(expectedTime);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				System.out.println("日期转换异常！");
			}
			opp.setUpdateTime(date);
			opp.setExpectedTime(date1);
			
			if(opdao.save(opp) != null){
				result.put("message", "保存成功！");
			}else{
				result.put("message", "保存失败！");
			}
		
		return result;
	}
	
	@GetMapping("savenew")
	@ResponseBody
	public JSONObject savenew(
			@RequestParam(value="updateTime") String updateTime,
			@RequestParam(value="expectedTime") String expectedTime,
			@RequestParam(value="topic") String topic,
			@RequestParam(value="customerid") Long customerid,
			@RequestParam(value="stage") String stage,@RequestParam(value="priority") int priority,
			@RequestParam(value="possibility") String possibility,@RequestParam(value="expectedMoney") double expectedMoney) {
			JSONObject result = new JSONObject();
			SalesOpportunity opp = new SalesOpportunity();
			opp.setCustomer(cusdao.findOne(customerid));
			opp.setExpectedMoney(expectedMoney);
			opp.setPossibility(possibility);
			opp.setPriority(priority);
			opp.setStage(stage);
			opp.setTopic(topic);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
			//转换时间
			Date date = null;
			Date date1=null;
			try {
				date = formatter.parse(updateTime);
				date1 = formatter.parse(expectedTime);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				System.out.println("日期转换异常！");
			}
			opp.setUpdateTime(date);
			opp.setExpectedTime(date1);
			
			if(opdao.save(opp) != null){
				result.put("message", "保存成功！");
			}else{
				result.put("message", "保存失败！");
			}
		return result;

	}
	
	
	
	/**
	 * 批量删除
	 */
	@PostMapping("delete/{id}")
	@Transactional
	@ResponseBody
	public JSONObject delete(@PathVariable Long[] id) {
		JSONObject result = new JSONObject();
		try {
			// 遍历id数组，先查询所有需要进行操作的对象
			for (int i = 0; i < id.length; i++) {
				SalesOpportunity sps = opdao.findOne(id[i]);
				sps.setDelete(true);
				opdao.save(sps);
			}
			result.put("success", true);
		} catch (Exception e) {
			result.put("errorMsg", e.getStackTrace());
		}
		return result;
	}

	/**
	 * @author PD 加载解决方案表格每一个解决方案的详细信息
	 * @return
	 */
	@RequestMapping("oppdetailsform/{id}")
	public String solutiondetailsform(@PathVariable(required = false) Long id, Model model) {

		return "beforesale/opportunity/oppdetailsform";
	}

	/**
	 * 图表数据
	 * 
	 * @author PD
	 * @return
	 */
	// @RequestMapping("oppdata")
	// @ResponseBody
	// public JSONArray getdata(Model model){
	// JSONArray jsonArray = new JSONArray();
	// List<SalesOpportunity> opplist = opdao.findAllByIsDelete(false);
	// for (SalesOpportunity opp : opplist) {
	// JSONObject jsonObject = new JSONObject();
	// jsonObject.put("money", opp.getExpectedMoney());
	// jsonObject.put("priority",opp.getPriority());
	// jsonArray.add(jsonObject);
	// // model.addAttribute("jsonArray", jsonArray);
	// }
	// return jsonArray;
	// }

	/**
	 * 查询所有销售机会主题
	 * 
	 * @author hzl
	 * @return
	 */
	@RequestMapping("opportunitylist")
	@ResponseBody
	public JSONArray getCustomer() {
		JSONArray jsonArray = new JSONArray();
		List<SalesOpportunity> opportunitylist = (List<SalesOpportunity>) opdao.findAll();
		if (opportunitylist.size() > 0) {
			for (SalesOpportunity opportunity : opportunitylist) {
				jsonArray.add(opportunity);
			}
		} else {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("id", null);
			jsonObj.put("topic", "没有相应的记录");
			jsonArray.add(jsonObj);
		}
		return jsonArray;
	}

	
	/**
	 * 根据客户id查询所有销售机会主题
	 * 
	 * @author hzl
	 * @return
	 */
	@RequestMapping("getOppByCus")
	@ResponseBody
	public JSONArray getOppByCus(@RequestParam("customerid") Long cid) {
		JSONArray jsonArray = new JSONArray();
		List<SalesOpportunity> opportunitylist = opdao.findByCustomer(cusdao.findOne(cid));
		if(opportunitylist.size()>0){
			for (SalesOpportunity opportunity : opportunitylist) {
				jsonArray.add(opportunity);
			}
		}else{
			JSONObject jsonObj=new JSONObject();
			jsonObj.put("id", null);
			jsonObj.put("topic", "没有相应的记录");
			jsonArray.add(jsonObj);
		}
		return jsonArray;
	}
	

	
	/**
	 * 新增竞争对手时，跟据当前登录的用户显示不同的销售机会
	 * @return
	 */
	@RequestMapping("getOppByEmp")
	@ResponseBody
	public JSONArray getOppByEmp(HttpSession session) {
		JSONArray result = new JSONArray();
		//从session里获取当前登录用户
		Employee emp = (Employee)session.getAttribute("employee");
		//判断当前登录用户的角色
		//如果是管理员则显示所有，如果是普通销售人员就只显示他自己的
		List<SalesOpportunity> opps = null;
		if (emp.getRole().getRoleName().equals("销售员")) {
			Long empid = emp.getId();
			opps = opdao.findByEmp(empid);
			if (opps.size() > 0) {
				for (SalesOpportunity salesOpportunity : opps) {
					result.add(salesOpportunity);
				}
			}else {
				JSONObject jo = new JSONObject();
				jo.put("id", null);
				jo.put("value", "没有相应的记录");
				result.add(jo);
			}
		}else {
			opps = opdao.findAllByIsDelete(false);
			if (opps.size() > 0) {
				for (SalesOpportunity salesOpportunity : opps) {
					result.add(salesOpportunity);
				}
			}else {
				JSONObject jo = new JSONObject();
				jo.put("id", null);
				jo.put("value", "没有相应的记录");
				result.add(jo);
			}
		}
		return result;
	}

	/**
	 * //根据角色查询销售机会
	 * @param sales
	 * @param session
	 */
	@PostMapping("search/{sales}")
	@ResponseBody
	public List<SalesOpportunity> search(@PathVariable String sales,HttpSession session){
		Employee employee = (Employee) session.getAttribute("employee");
		Long empid = employee.getId();
		List<SalesOpportunity> 	salespportunitys = oppmapper.selectOpp(empid, sales);
		return salespportunitys;
	}

	/**
	 * //模糊查询所有销售机会
	 * @param sales
	 * @param session
	 */
	@PostMapping("search2/{sales}")
	@ResponseBody
	public List<SalesOpportunity> search2(@PathVariable String sales){
		List<SalesOpportunity> 	salespportunitys = oppmapper.selectAllOpp(sales);
		return salespportunitys;
	}
	
}
